package com.yxuan.springboot.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.yxuan.springboot.WxPayUtil.HttpUtils;
import com.yxuan.springboot.constant.SystemConstant;
import com.yxuan.springboot.model.*;
import com.yxuan.springboot.service.*;
import com.yxuan.springboot.util.*;

import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zchao
 * UserLogin控制器
 * @date 2023-05-09 11:17:04
 */
@Slf4j
@Controller
@Api(tags = "用户登录表")
@RequestMapping(value = "/userlogin", method = {RequestMethod.POST, RequestMethod.GET})
public class UserLoginController extends BaseController<UserLogin> {


    @Value("${weixin.appid}")
    private String APP_ID;
    @Value("${weixin.appsecret}")
    private String APP_SECRET;
    @Value("${douyin.appid}")
    private String DY_APP_ID;
    @Value("${douyin.appsecret}")
    private String DY_APP_SECRET;

    @Autowired
    private UserLoginService userLoginService;
    @Autowired
    private UserVipService userVipService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private UserInformationService userInformationService;
    @Autowired
    private ThirdTokenService thirdTokenService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SetsCollectionsService setsCollectionsService;

    @Resource(name = "wxPayClient")
    private CloseableHttpClient dyPayClient;

    private static final int TYPE_NORMAL = 0;
    private static final String NATION_CODE = "86";

    //根据手机号发送验证码
    @ResponseBody
    @RequestMapping(value = "/sendCode", method = RequestMethod.POST)
    public Result sendCode(@RequestBody UserLogin userLogin) throws Exception {

//
//        int appid = 1400827803;
//        String appkey = "374a4f041ae8f1355980051ec4391d1c";
//        int templateId = 1821837; //模板ID
//        String smsSign = "武汉工职教育咨询有限公司";


        //校验手机号是否存在
        log.info("校验手机号是否存在");
        UserLogin admin = userLoginService.findObjectByPramas(userLogin);
        log.info("查询到的用户:" + admin);
        if (admin == null) {
            //若不存在则自动创建该用户（即自动注册）
            //设置当前添加的时间
            Date date = new Date(System.currentTimeMillis());
            SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            Date AppliedTime = formatter.parse(formatter.format(date));
            userLogin.setCreateTime(AppliedTime);
            userLogin.setEndTime(AppliedTime);
            userLogin.setBlacklist("0");
            //userVip.setUsername(userLogin.getPhoneNumber());

            //设置逻辑删除:0未删除,1已删除
            //userLogin.setDeleted("0");
            //添加用户
            log.info("添加用户");
            userLoginService.save(userLogin);
            //获取用户userid(login表id)
            UserLogin login1 = userLoginService.findObjectByPramas(userLogin);
            UserVip userVip = new UserVip();
            // userVip.setDeleted("0");
            userVip.setUserId(login1.getId());
            userVip.setVipRank("0");
            userVip.setCourseSelectionTimes("0");
            userVip.setFillingTimes("0");
            userVip.setProbabilityTimes("1");
            userVip.setTimeBuying(AppliedTime);
            userVip.setInfoUpdTimes("1");
            userVip.setGptTimes("3");
            //userVip.setLeftTimes("0");
            //userVip.setExpired(0);
            log.info("添加vip数据");
            userVipService.save(userVip);

            //设置userInformation默认值
            UserInformation userInformation = new UserInformation();
            userInformation.setUserId(login1.getId());
            userInformation.setHeadImage("https://editor-md-1317285847.cos.ap-beijing.myqcloud.com/null/260191685253771311.png");
            String uuid = UUIDUtil.getUUID();
            userInformation.setUserName("用户" + userLogin.getPhoneNumber().substring(userLogin.getPhoneNumber().length() - 5));
            userInformation.setPhoneNumber(login1.getPhoneNumber());
            userInformation.setVipRank("0");
            Date date1 = DaysCalculateUtil.targetDate(AppliedTime, 0, 0, -1);
            userInformation.setUpdTime(date1);
            log.info("添加用户默认信息");
            userInformationService.save(userInformation);
            //发送验证码

            log.info("发送验证码");
//                String[] params = {login1.getVerificationCode()}; //短信中的参数
//                SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
//                SmsSingleSenderResult result = ssender.sendWithParam("86", login1.getPhoneNumber(), templateId,
//                        params, smsSign, "", "");

//                String msg="验证码为："+login1.getVerificationCode()+"，您正在登录，若非本人操作，请勿泄露。";
//                SmsSingleSenderResult send = ssender.send(TYPE_NORMAL, NATION_CODE, admin.getPhoneNumber(), msg, "", "");
            //发送验证码,发送验证码的方法里自带生成验证码并根据手机号存储
            boolean send = smsService.send(login1.getPhoneNumber());
            if (send) {
                return new Result(send, SUCCESSCODE, "发送验证码成功");
            }

            return new Result(FAILCODE, "发送验证码失败");


        } else {
            //手机号已存在
            log.info("手机号已存在");
            //获取手机号，生成并存储验证码
            //更改用户ip
            UserLogin login1 = new UserLogin();
            login1.setPhoneNumber(admin.getPhoneNumber());
            login1.setIp(userLogin.getIp());
            login1.setId(admin.getId());

            userLoginService.upd(login1);

            //发送验证码,发送验证码的方法里自带生成验证码并根据手机号存储
            boolean send = smsService.send(admin.getPhoneNumber());
            if (send) {
                return new Result(send, SUCCESSCODE, "发送验证码成功");
            }

            return new Result(FAILCODE, "发送验证码失败");


        }
    }


    /**
     * 通过验证码登录
     */
    @RequestMapping("/login")
    @ResponseBody
    public Result login(@RequestBody UserLogin userlogin) throws Exception {
        Map<String, Object> result = new HashMap<>();
        //校验手机号是否存在(理论上没有手机号不存在的情况，因为在发送验证码时就一并根据手机号注册了)
        log.info("打印UserLogin:" + userlogin);

        UserLogin login1 = new UserLogin();
        login1.setPhoneNumber(userlogin.getPhoneNumber());
        UserLogin admin = userLoginService.findObjectByPramas(login1);
        log.info("打印查询出来的login" + admin);

        if (admin != null) {
            //校验验证码是否一致
            log.info("校验验证码是否一致");
            boolean equalsVCode = admin.getVerificationCode().equals(userlogin.getVerificationCode());
            if (equalsVCode) {
                //手机号存在，且验证码一致登入成功
                log.info("手机号存在，且验证码一致登入成功");
                result.put("Id", admin.getId());
                //新建JWT加密对象
                log.info("新建JWT加密对象");
                UserLogin JWTEmployee = new UserLogin();
                JWTEmployee.setPhoneNumber(admin.getPhoneNumber());


                //把token返回给客户端-->客户端保存至localStorage-->客户端每次请求附带localStorage参数
                //JSON.toJSONString(admin):将JSON对象转为字符串
                //SystemConstant.JWT_TTL：token有效时间
                String JWT = JwtUtil.createJWT("1", JSON.toJSONString(JWTEmployee), SystemConstant.JWT_TTL);
                //新建员工对象，用于存放修改之后的JWT,
                UserLogin returnLogin = new UserLogin();
                returnLogin.setPhoneNumber(userlogin.getPhoneNumber());
                returnLogin.setToken(JWT);
                log.info("token:" + JWT);
                userLoginService.upd(returnLogin);


                result.put("token", JWT);
                result.put("userId", admin.getId());
                return new Result(result, SUCCESSCODE, "登录成功");
            }
            //登录失败 ，验证码错误
            result.put("success", false);
            result.put("msg", "验证码错误,请重新输入!");
            return new Result(result, FAILCODE);
        }
        //理论上没有这个报错
        result.put("success", false);
        result.put("msg", "用户名错误或不存在!");
        return new Result(result, FAILCODE);
    }


    /**
     * @className: EmployeeController.java
     * @methodName: refreshToken
     * @effect: 刷新用户token
     * @author: JingxuanFan
     * @date: 2023/3/26 18:56
     **/
    @GetMapping(value = "/refreshToken")
    @ResponseBody
    public Map<Object, Object> refreshToken(HttpServletRequest request, UserLogin userlogin) throws Exception {
        Map<Object, Object> result = new HashMap<>();
        //旧的token令牌
        log.info("旧的token令牌:" + request.getHeader("token"));
        //1.获取页面传过来的旧的token
        String oldToken = request.getHeader("token");
        //2.根据主键Id获取数据库中的token，进行比较
        String queryToken = userLoginService.findTById(String.valueOf(userlogin.getId())).getToken();
        if (oldToken.equals(queryToken)) {
            //3.解析旧的token
            Claims claims = JwtUtil.parseJWT(oldToken);
            //4.获取JWT解密对象claims 中的身份账号，密码信息
            String subject = claims.getSubject();
            log.info("解密token后的身份信息" + subject);
            //5.根据身份解密的对象信息生成新的token
            String JWT = JwtUtil.createJWT(userlogin.getId().toString(), subject, SystemConstant.JWT_TTL);
            log.info("新的token令牌：" + JWT);
            result.put("JWT", JWT);
            //6.获取主键Id,创建Login对象，修改数据库中的token
            UserLogin updLogin = new UserLogin();
            updLogin.setId(userlogin.getId());
            updLogin.setToken(JWT);
            userLoginService.upd(updLogin);
            return result;
        } else {
            log.info("token验证有误");
            result.put("state", "token验证有误");
            result.put("code", Code.TOKEN_OUTDATED);
            return result;
        }
    }


    /**
     * 传userId,查信息表里有无该userId的数据，有返回true,无false
     */
    @RequestMapping("/imformationStatus")
    @ResponseBody
    public Result imformationStatus(@RequestBody UserInformation userInformation) throws Exception {

        UserInformation objectByPramas = userInformationService.findObjectByPramas(userInformation);
        if (objectByPramas.getGaokaoGrade() == null) {
            return new Result(false, SUCCESSCODE, "用户未完善信息");
        }
        return new Result(true, SUCCESSCODE, "用户已完善信息");

    }


    /**
     * 微信登录
     * @param code
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/wxlogin")
    public Result wxCallback(String code) throws Exception {

        try {
            log.info("code:" + code);
            //String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APP_ID + "&secret=" + APP_SECRET + "&code=" + code + "&grant_type=authorization_code";
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APP_ID + "&secret=" + APP_SECRET + "&js_code=" + code + "&grant_type=authorization_code";

            log.info("url:" + url);
            String result = HttpUtils.sendGet(url);
            JSONObject jsonObject = JSONObject.parseObject(result);
            log.info("获取到的微信登录回调结果" + jsonObject.toJSONString());
            String accessToken = jsonObject.getString("access_token");
            String openId = jsonObject.getString("openid");
            UserLogin userLogin = new UserLogin();
            userLogin.setOpenId(openId);
            userLogin.setAccessToken(accessToken);
            log.info("openid:" + openId);
            log.info("accessToken:" + accessToken);
            if(openId.isEmpty()||openId==null){
                return new Result(201,"openid为空");
            }
            //根据phoneNumber查询用户是否存在，存在就将openid进去，不在就创建新用户
            //根据openid查询用户是否存在，不在就创建新用户
            UserLogin userLoginPho = new UserLogin();
            userLoginPho.setOpenId(openId);
            UserLogin targetPho = userLoginService.findObjectByPramas(userLoginPho);
            if (targetPho == null) {
                log.info("用户不存在，执行注册");
                //若不存在则自动创建该用户（即自动注册）
                //设置当前添加的时间
                Date date = new Date(System.currentTimeMillis());
                SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                Date AppliedTime = formatter.parse(formatter.format(date));
                userLogin.setCreateTime(AppliedTime);
                userLogin.setEndTime(AppliedTime);
                userLogin.setBlacklist("0");
                userLogin.setOpenId(openId);
                userLogin.setAccessToken(accessToken);
                //生成11位永不重复的数用来替代phoneNumber
                SetsCollections setsCollections = new SetsCollections();
                int uniqueNumber;
                do {
                    uniqueNumber = UniqueNumberGenerator.generateUniqueNumber();
                    setsCollections.setSetsnum(String.valueOf(uniqueNumber));

                } while (setsCollectionsService.findObjectByPramas(setsCollections) != null);
                log.info("虚拟手机号为:" + uniqueNumber);
                userLogin.setPhoneNumber(String.valueOf(uniqueNumber));
                log.info("添加用户");
                userLoginService.save(userLogin);


                //获取用户userid(login表id)
                UserLogin login1 = userLoginService.findObjectByPramas(userLogin);

                //添加set
                SetsCollections setsCollections1 = new SetsCollections();
                setsCollections1.setUserId(login1.getId());
                setsCollections1.setSetsnum(String.valueOf(uniqueNumber));
                setsCollectionsService.save(setsCollections1);
                log.info("修改set成功");

                UserVip userVip = new UserVip();
                // userVip.setDeleted("0");
                userVip.setUserId(login1.getId());
                userVip.setVipRank("0");
                userVip.setCourseSelectionTimes("0");
                userVip.setFillingTimes("0");
                userVip.setProbabilityTimes("1");
                userVip.setTimeBuying(AppliedTime);
                userVip.setInfoUpdTimes("1");
                userVip.setGptTimes("3");
                log.info("添加vip数据");
                userVipService.save(userVip);

                //设置userInformation默认值
                UserInformation userInformation = new UserInformation();
                userInformation.setUserId(login1.getId());
                userInformation.setHeadImage("https://editor-md-1317285847.cos.ap-beijing.myqcloud.com/null/260191685253771311.png");
                userInformation.setUserName("用户" + userLogin.getPhoneNumber().substring(userLogin.getPhoneNumber().length() - 5));
                userInformation.setPhoneNumber(login1.getPhoneNumber());
                userInformation.setVipRank("0");
                Date date1 = DaysCalculateUtil.targetDate(AppliedTime, 0, 0, -1);
                userInformation.setUpdTime(date1);
                log.info("添加用户默认信息");
                userInformationService.save(userInformation);


                //新建员工对象，用于存放修改之后的JWT,
                UserLogin returnLogin = new UserLogin();
                returnLogin.setOpenId(userLogin.getOpenId());
                returnLogin.setPhoneNumber(String.valueOf(uniqueNumber));


                //生成uuid作为phoneNumber以及vip的username
                // String wxuuid = UUID.randomUUID().toString().replaceAll("-", "");

                //returnLogin.setPhoneNumber(finaluuid);

                //新建JWT加密对象
                log.info("新建JWT加密对象");
                UserLogin JWTEmployee = new UserLogin();
                JWTEmployee.setPhoneNumber(returnLogin.getPhoneNumber());
                //把token返回给客户端-->客户端保存至localStorage-->客户端每次请求附带localStorage参数
                //JSON.toJSONString(admin):将JSON对象转为字符串
                //SystemConstant.JWT_TTL：token有效时间
                String JWT = JwtUtil.createJWT("1", JSON.toJSONString(JWTEmployee), SystemConstant.JWT_TTL);
                returnLogin.setToken(JWT);
                log.info("token:" + JWT);
                log.info(("修改token的login:" + returnLogin.toString()));
                //微信登录修改对应用户数据
                userLoginService.Wxlogin(returnLogin);
                Map<Object, Object> map = new HashMap<>();
                map.put("token", JWT);
                map.put("userId", login1.getId());
                return new Result(map, SUCCESSCODE, "登录/注册成功");


            }


            //根据openId注册或登录
            //验证用户是否存在（根据openId查询是否存在微信用户）
            //UserLogin targetWxLogin = userLoginService.findByOpenId(userLogin.getOpenId());
            //如果不存在则注册
//            if (targetWxLogin == null) {
//            }

            //新建员工对象，用于存放修改之后的JWT,
            //用户存在，直接修改token
            UserLogin login1 = new UserLogin();
            login1.setOpenId(openId);
            //拿取openid查询出来的对象的phoneNumber作为token的phoneNumber

            login1.setPhoneNumber(targetPho.getPhoneNumber());
            login1.setAccessToken(accessToken);
            //新建JWT加密对象
            log.info("新建JWT加密对象");
            UserLogin JWTEmployee = new UserLogin();
            JWTEmployee.setPhoneNumber(targetPho.getPhoneNumber());
            //把token返回给客户端-->客户端保存至localStorage-->客户端每次请求附带localStorage参数
            //JSON.toJSONString(admin):将JSON对象转为字符串
            //SystemConstant.JWT_TTL：token有效时间
            String JWT = JwtUtil.createJWT("1", JSON.toJSONString(JWTEmployee), SystemConstant.JWT_TTL);
            login1.setToken(JWT);
            log.info("token:" + JWT);
            //微信登录修改对应用户数据
            userLoginService.Wxlogin(login1);

            Map<Object, Object> map = new HashMap<>();
            map.put("token", JWT);
            map.put("userId", targetPho.getId());
            return new Result(map, SUCCESSCODE, "登录/注册成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(FAILCODE, "登录/注册失败");

        }


    }


    // 更新token
    @ApiOperation(value = "更新token", notes = "更新token")
    @RequestMapping("/reloadtoken")
    @ResponseBody
    public String reloadToken() {
        // 获取token Url
        String CodeToOpenId = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APP_SECRET;
        // String 接受参数
        String result = restTemplate.getForObject(CodeToOpenId, String.class);
        // 获取结果转 json
        System.out.println(result);
        JSONObject jsonObject = JSON.parseObject(result);
        // json中获取 id
        String access_token = (String) jsonObject.get("access_token");
        try {
//            Date now2 = Calendar.getInstance().getTime();
            ThirdToken firm = new ThirdToken();
            firm.setAccessToken(access_token);
//            firm.setId(1L);
//            firm.setCreated(now2);
            firm.setTokenType("小程序token");

            thirdTokenService.upd(firm);
            return BaseController.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
//            String toCreator = "576534286@qq.com"; // 接收者邮箱
//            String title = "刷新Token异常";
//            String content = "token刷新异常";
//            emailUtil.sendMessage(toCreator, title, content);
            return BaseController.ERROR;
        }
    }

    // 更新token
    @ApiOperation(value = "更新抖音token", notes = "更新抖音token")
    @RequestMapping("/reloadDouyintoken")
    @ResponseBody
    public String reloadDouyintoken() {
        Map<String, Object> parame = new LinkedHashMap<>();

        //抖音小程序app
        parame.put("appid", DY_APP_ID);
        // 商户订单编号
        parame.put("secret", DY_APP_SECRET);

        parame.put("grant_type", "client_credential");        //小程序用户的 open_id，通过 code2Session 获取


        try {
            Map<String,Object> getpost = DouyinPayController.getDDpost(parame, dyPayClient);
            String accessToken = (String) ((Map<String, Object>)getpost.get("data")).get("access_token");
            log.info("access_token"+accessToken);
            log.info("getpost"+getpost);
            ThirdToken firm = new ThirdToken();
            firm.setAccessToken(accessToken);
            firm.setTokenType("抖音小程序token");
            thirdTokenService.upd(firm);
            return BaseController.SUCCESS;
        }catch (Exception e) {
            e.printStackTrace();

            return BaseController.ERROR;
        }

    }





    /**
     * 根据code获取用户信息
     *
     * @param code
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "getPhoneNumber", notes = "getPhoneNumber")
    @RequestMapping("/getPhoneNumberByWx")
    @ResponseBody
    public Result getPhoneNumber(String code) throws Exception {

        ThirdToken thirdToken = new ThirdToken();
        thirdToken.setTokenType("小程序token");
        ThirdToken targetThirdToken = thirdTokenService.findObjectByPramas(thirdToken);

        String codeurl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + targetThirdToken.getAccessToken();
//        String forObject = restTemplate.getForObject(codeurl, String.class);
//        JSONObject jsonObject =  JSON.parseObject(forObject);

        // 设置请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("code", code);


        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
// 创建请求体
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, headers);

// 发起POST请求
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(codeurl, requestEntity, String.class);

// 获取响应结果
        String responseBody = responseEntity.getBody();
        JSONObject jsonObject = JSON.parseObject(responseBody);

        return new Result(jsonObject, SUCCESSCODE, "获取信息成功");


    }


    /**
     * 抖音登录
     *
     * @param code
     * @return
     */
    @ResponseBody
    @RequestMapping("/douyinlogin")
    public Result dyLogin(String code) {


        try {
//            log.info("code:" + code);
//            String url = "https://developer.toutiao.com/api/apps/v2/jscode2session?appid=" + DY_APP_ID + "&secret=" + DY_APP_SECRET + "&js_code=" + code + "&grant_type=authorization_code";
//            log.info("url:" + url);
//            String result = HttpUtils.sendGet(url);
//            JSONObject jsonObject = JSONObject.parseObject(result);

//            String url = "https://developer.toutiao.com/api/apps/v2/jscode2session";
            String url = "https://open-sandbox.douyin.com/api/apps/v2/jscode2session";
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            log.info("code:" + code);
// 设置请求方法为POST
            con.setRequestMethod("POST");

// 设置请求头
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("User-Agent", "Mozilla/5.0");

// 设置请求体
            JSONObject requestParams = new JSONObject();
            requestParams.put("appid", DY_APP_ID);
            requestParams.put("secret", DY_APP_SECRET);
            requestParams.put("code", code);
            requestParams.put("grant_type", "authorization_code");
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(requestParams.toString());
            wr.flush();
            wr.close();

// 发送请求，获取响应结果
            int responseCode = con.getResponseCode();
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

// 解析响应结果，进行业务逻辑处理
            JSONObject jsonObject = JSONObject.parseObject(response.toString());

            log.info("获取到的抖音登录回调结果" + jsonObject.toJSONString());
            JSONObject data1 = JSONObject.parseObject(jsonObject.getString("data"));

            String unionid = data1.getString("unionid");
            String openId = data1.getString("openid");
            UserLogin userLogin = new UserLogin();
            userLogin.setOpenId(openId);
            userLogin.setAccessToken(unionid);
            log.info("openid:" + openId);
            log.info("unionid:" + unionid);

            //根据phoneNumber查询用户是否存在，存在就将openid进去，不在就创建新用户
            //根据openid查询用户是否存在，不在就创建新用户
            UserLogin userLoginPho = new UserLogin();
            openId="dy"+openId;
            userLoginPho.setOpenId(openId);
            log.info("查询抖音用户");
            UserLogin targetPho = userLoginService.findObjectByPramas(userLoginPho);
            if (targetPho == null) {
                log.info("用户不存在，执行注册");
                //若不存在则自动创建该用户（即自动注册）
                //设置当前添加的时间
                Date date = new Date(System.currentTimeMillis());
                SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                Date AppliedTime = formatter.parse(formatter.format(date));
                userLogin.setCreateTime(AppliedTime);
                userLogin.setEndTime(AppliedTime);
                userLogin.setBlacklist("0");
                userLogin.setOpenId(openId);
                userLogin.setAccessToken(unionid);
                //生成11位永不重复的数用来替代phoneNumber
                SetsCollections setsCollections = new SetsCollections();
                int uniqueNumber;
                do {
                    uniqueNumber = UniqueNumberGenerator.generateUniqueNumber();
                    setsCollections.setSetsnum(String.valueOf(uniqueNumber));

                } while (setsCollectionsService.findObjectByPramas(setsCollections) != null);
                log.info("虚拟手机号为:" + uniqueNumber);
                userLogin.setPhoneNumber(String.valueOf(uniqueNumber));
                log.info("添加用户");
                userLoginService.save(userLogin);


                //获取用户userid(login表id)
                UserLogin login1 = userLoginService.findObjectByPramas(userLogin);

                //添加set
                SetsCollections setsCollections1 = new SetsCollections();
                setsCollections1.setUserId(login1.getId());
                setsCollections1.setSetsnum(String.valueOf(uniqueNumber));
                setsCollectionsService.save(setsCollections1);
                log.info("修改set成功");

                UserVip userVip = new UserVip();
                // userVip.setDeleted("0");
                userVip.setUserId(login1.getId());
                userVip.setVipRank("0");
                userVip.setCourseSelectionTimes("0");
                userVip.setFillingTimes("0");
                userVip.setProbabilityTimes("1");
                userVip.setTimeBuying(AppliedTime);
                userVip.setInfoUpdTimes("1");
                userVip.setGptTimes("3");
                log.info("添加vip数据");
                userVipService.save(userVip);

                //设置userInformation默认值
                UserInformation userInformation = new UserInformation();
                userInformation.setUserId(login1.getId());
                userInformation.setHeadImage("https://editor-md-1317285847.cos.ap-beijing.myqcloud.com/null/260191685253771311.png");
                userInformation.setUserName("用户" + userLogin.getPhoneNumber().substring(userLogin.getPhoneNumber().length() - 5));
                userInformation.setPhoneNumber(login1.getPhoneNumber());
                userInformation.setVipRank("0");
                Date date1 = DaysCalculateUtil.targetDate(AppliedTime, 0, 0, -1);
                userInformation.setUpdTime(date1);
                log.info("添加用户默认信息");
                userInformationService.save(userInformation);


                //新建员工对象，用于存放修改之后的JWT,
                UserLogin returnLogin = new UserLogin();
                returnLogin.setOpenId(userLogin.getOpenId());
                returnLogin.setPhoneNumber(String.valueOf(uniqueNumber));


                //生成uuid作为phoneNumber以及vip的username
                // String wxuuid = UUID.randomUUID().toString().replaceAll("-", "");

                //returnLogin.setPhoneNumber(finaluuid);

                //新建JWT加密对象
                log.info("新建JWT加密对象");
                UserLogin JWTEmployee = new UserLogin();
                JWTEmployee.setPhoneNumber(returnLogin.getPhoneNumber());
                //把token返回给客户端-->客户端保存至localStorage-->客户端每次请求附带localStorage参数
                //JSON.toJSONString(admin):将JSON对象转为字符串
                //SystemConstant.JWT_TTL：token有效时间
                String JWT = JwtUtil.createJWT("1", JSON.toJSONString(JWTEmployee), SystemConstant.JWT_TTL);
                returnLogin.setToken(JWT);
                log.info("token:" + JWT);
                log.info(("修改token的login:" + returnLogin.toString()));
                //抖音登录修改对应用户数据
                userLoginService.Wxlogin(returnLogin);
                Map<Object, Object> map = new HashMap<>();
                map.put("token", JWT);
                map.put("userId", login1.getId());
                return new Result(map, SUCCESSCODE, "登录/注册成功");


            }


            //根据openId注册或登录
            //验证用户是否存在（根据openId查询是否存在微信用户）
            //UserLogin targetWxLogin = userLoginService.findByOpenId(userLogin.getOpenId());
            //如果不存在则注册
//            if (targetWxLogin == null) {
//            }

            //新建员工对象，用于存放修改之后的JWT,
            //用户存在，直接修改token
            UserLogin login1 = new UserLogin();
            login1.setOpenId(openId);
            //拿取openid查询出来的对象的phoneNumber作为token的phoneNumber

            login1.setPhoneNumber(targetPho.getPhoneNumber());
            login1.setAccessToken(unionid);
            //新建JWT加密对象
            log.info("新建JWT加密对象");
            UserLogin JWTEmployee = new UserLogin();
            JWTEmployee.setPhoneNumber(targetPho.getPhoneNumber());
            //把token返回给客户端-->客户端保存至localStorage-->客户端每次请求附带localStorage参数
            //JSON.toJSONString(admin):将JSON对象转为字符串
            //SystemConstant.JWT_TTL：token有效时间
            String JWT = JwtUtil.createJWT("1", JSON.toJSONString(JWTEmployee), SystemConstant.JWT_TTL);
            login1.setToken(JWT);
            log.info("token:" + JWT);
            //微信登录修改对应用户数据
            userLoginService.Wxlogin(login1);

            Map<Object, Object> map = new HashMap<>();
            map.put("token", JWT);
            map.put("userId", targetPho.getId());
            return new Result(map, SUCCESSCODE, "登录/注册成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(FAILCODE, "登录/注册失败");

        }


    }


}
